package com.dd.edu.flashsale.portal.controller;

import com.dd.edu.flashsale.portal.entity.Order;
import com.dd.edu.flashsale.portal.entity.OrderStatus;
import com.dd.edu.flashsale.portal.service.OrderService;
import com.dd.edu.flashsale.portal.utils.Message;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取下单地址：用于隐藏秒杀地址
     * @param order
     * @return
     */
    @PostMapping("/getMSAddr")
    public Message getOrderUrl(Order order) {

        //获取动态秒杀地址
        final String pathId = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(String.format("MSPathKey_%s", order.getUserId()), pathId);
        return Message.success(String.format("/%s/MSOrder", pathId));
    }


    /**
     * 真实下单地址
     * @param order
     * @return
     */
    @PostMapping("/{pathId}/MSOrder")
    public Message order(Order order, @PathVariable("pathId") String pathId) {

        // 校验请求地址的合法性
        final String key = String.format("MSPathKey_%s", order.getUserId());
        final Object o = redisTemplate.opsForValue().get(key);
        if (Objects.isNull(o) || !pathId.equals(o.toString())) {
            System.out.println("请求地址不合法");
            return Message.fail("请求地址不合法");
        }


        if (orderService.createOrder(order)) {
            return Message.success(order);
        } else {
            return Message.fail("抢购失败，请稍后再试");
        }
    }
}
